#include "UdpReceiver.h"
#include <QDebug>

UdpReceiver::UdpReceiver(QObject *parent)
    : QThread(parent), m_socket(nullptr), m_port(0)
{
}

UdpReceiver::~UdpReceiver()
{
    quit();
    wait();
    if (m_socket) {
        delete m_socket;
        m_socket = nullptr;
    }
}

void UdpReceiver::setPort(quint16 port)
{
    m_port = port;
}

void UdpReceiver::run()
{
    if (m_port == 0) {
        emit errorOccurred("未设置端口");
        return;
    }
    
    m_socket = new QUdpSocket();
    if (!m_socket->bind(QHostAddress::Any, m_port)) {
        emit errorOccurred(QString("绑定端口失败: %1").arg(m_socket->errorString()));
        delete m_socket;
        m_socket = nullptr;
        return;
    }
    
    connect(m_socket, &QUdpSocket::readyRead, this, &UdpReceiver::onReadyRead, Qt::DirectConnection);
    qInfo() << "UDP接收线程启动，监听端口:" << m_port;
    
    exec(); // 启动事件循环
}

void UdpReceiver::onReadyRead()
{
    while (m_socket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(m_socket->pendingDatagramSize());
        
        QHostAddress sender;
        quint16 senderPort;
        qint64 bytesRead = m_socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        
        if (bytesRead != datagram.size()) {
            emit errorOccurred("读取数据不完整");
            continue;
        }
        
        // 320x256 16位灰度图的预期大小
        const int expectedSize = 320 * 256 * 2;
        if (datagram.size() != expectedSize) {
            emit errorOccurred(QString("数据大小不符，预期 %1 字节，实际 %2 字节")
                              .arg(expectedSize).arg(datagram.size()));
            continue;
        }
        
        emit dataReceived(datagram);
    }
}
